<template>
  <div>
    <el-dialog @update:modelValue="close" :modelValue="props.dialogVisible" title="忘记密码" width="600px" @open="open">
      <el-form label-width="0" ref="form" :model="formData" :rules="rules">
        <el-row class="el-row-override" :gutter="2">
          <el-col :span="24">
            <el-form-item prop="userName">
              <el-input @blur="handleBlur" placeholder="请输入用户名" clearable v-model="formData.userName" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="password">
              <el-input type="password" placeholder="请输入新密码" clearable v-model="formData.password" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="checkPass">
              <el-input type="password" placeholder="请输入确认密码" clearable v-model="formData.checkPass" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="phone">
              <el-input readonly placeholder="11位手机号" clearable v-model="formData.phone" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item style="width: 100%;" prop="code">
              <el-row style="width: 100%;">
                <el-col :span="24">
                  <el-input style="width: 100%;" placeholder="请输入短信验证码" v-model="formData.code">
                    <template #prefix>
                      <img
                        style="width: 12px"
                        src=""
                      />
                    </template>
                    <template #append>
                      <el-button plain type="primary" @click="getMessageCode" :disabled="!formData.phone || isCounting"> {{ isCounting ? `${countdown} 秒后重新发送` : '获取验证码' }} </el-button>
                    </template>
                  </el-input>
                </el-col>
            </el-row>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getTunnel } from '@/api/login'
import { to } from 'await-to-js';
import { useCountdown } from '@/hooks/useCountdown';

const emit = defineEmits<{
  (e: 'onClose', detail: boolean): void
}
>();

const submitLoading = ref(false);

const form = ref<ElFormInstance>();

const tunnelList = ref([])

interface MyComponentProps {
  dialogVisible: boolean;
  userId: number;
  optionalConfig?: Record<string, any>; // 可选的配置对象
}
const props = defineProps<MyComponentProps>();

const formData = reactive({
    userName: '',
    verifyCode: '',
    code:'',
    password: '',
    phone: '',
    checkPass: ''
})


const countdown = ref(60);
const isCounting = ref(false);
const intervalId = ref();

  const startCountdown = (): void => {
    if (!isCounting.value) {
      isCounting.value = true;
      intervalId.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(intervalId.value);
          isCounting.value = false;
          countdown.value = 60;
        }
      }, 1000);
    }
  };


const open = ()=>{

  formData.userName = '';
  formData.verifyCode = '';
  formData.code = '';
  formData.password = '';
  formData.phone = '';
  formData.checkPass = '';
  countdown.value = 60;
  isCounting.value = false;
 clearInterval(intervalId.value);
}


const getMessageCode = () => {
  startCountdown()

  useRequest('/system/user/sendForgotSmsCode', 'POST', {
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
    data: {
      domain: window.location.origin,
      userName: formData.userName
    }
  }, {
    immediate: true,
    onSuccess: () => {
      ElMessage.success('获取成功')
    }
   })

}

const handleBlur = () => {
  const { data } = useRequest('/system/user/getPhonenumber', 'POST', { headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  } ,data: { userName: formData.userName }}, { immediate: true })

  formData.phone = data as any


}

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (formData.checkPass !== '') {
      if (!form.value) return
      form.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value !== formData.password) {
    callback(new Error("两次输入的密码不一致!"))
  } else {
    callback()
  }
}

const rules = reactive({
  password: [
    { validator: validatePass, message: '请输入新密码', trigger: 'blur' },
    { required: true }
  ],
  checkPass: [{ validator: validatePass2, trigger: 'blur' },
    { required: true , message: '请输入确认密码'}
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' }
  ],

  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
})


const onSubmit = () => {
  form.value?.validate(async (valid) => {
      if (valid) {
         console.log(formData);
          submitLoading.value = true;
          const { code} = useRequest('/system/user/forgotPassword','POST', {
            headers: { isEncrypt: true },
            data: formData
          }, {
        immediate: true,
        onSuccess: (res) => {
          console.log(res);
          ElMessage.success('操作成功')
          submitLoading.value = false;
          emit('onClose', false);
        }
   })
  submitLoading.value = false;
          // if (code === 200) {
            // ElMessage.success('操作成功')
          // }
      }
  })
}

const close = () => {
  emit('onClose', false);
}
const getTunnelList = async () => {
  const [err, res] = await to(getTunnel())
  if (err) {
      return
  }
  if (res?.code === 200) {
      tunnelList.value = res?.data || []
  }
}

onMounted(() => {
  // getTunnelList()
})
</script>
<style lang="scss" scoped>
.el-row-override {
 .el-form-item {
  margin-bottom: 20px;
  .el-input {
    width: 100%;
  }
 }
}
</style>
